package classroom;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.project.institute.DAO.InstituteListFragmentDAO;
import com.project.trac.R;

import core.modules.DatabaseConnector;

public class MessageBoard extends InstituteListFragmentDAO {

	public static ListFragment newInstance(Context context) {
		MessageBoard lf = new MessageBoard();
		return lf;
	}

	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		
		ViewGroup root = (ViewGroup) inflater.inflate(R.layout.generic_list, null);
		
		new AsynchronousTask().execute();

		return root;
	}

	@Override
	public void onListItemClick(ListView l, View view, int pos, long id) {
		
		String item = l.getItemAtPosition(pos).toString().replace("=", "");
		
		int isThread = Integer.valueOf(item.subSequence(item.indexOf("thread")+6, item.indexOf("}")).toString());
		int forumID = Integer.valueOf(item.subSequence(item.indexOf("forum_id")+8, item.indexOf(", end")).toString());
		String TITLE = item.substring(item.indexOf("title")+5, item.indexOf(", started"));

		switch (isThread) {
		case 1:
			startActivity(new Intent(getActivity(), FileUpload.class).putExtra("forumID", forumID));
			break;
		case 2:
			startActivity(new Intent(getActivity(), common.Forum.ActivityManager.class)
			.putExtra("forumID", forumID)
			.putExtra("TITLE", TITLE));
			break;
		case 3:
			Toast.makeText(getActivity(), "not yet implemented - view thread (reply)", Toast.LENGTH_SHORT).show();
			break;
		
		}
	}

	public void onBackPressed() {
		super.getActivity().onBackPressed();
	}
	
	public void onAttachedToWindow() {
		super.getActivity().onAttachedToWindow();
		Window window = getActivity().getWindow();
		window.setFormat(PixelFormat.RGBA_8888);
	}
	
	private class AsynchronousTask extends AsyncTask<String, String, String> {

		HashMap<String, String> m;
		ArrayList<HashMap<String, String>> arrayList = new ArrayList<HashMap<String, String>>();

		ProgressDialog progressDialog;
		ListAdapter listAdapter;

		int rowCount;

		String KEY_TITLE = "title";
		String KEY_PERSON = "person";
		String KEY_DATE_STARTED = "started";
		String KEY_DATE_END = "end";
		String KEY_IS_THREAD = "thread";
		String KEY_FORUM_ID= "forum_id";

		protected void onPreExecute() {
			super.onPreExecute();
			progressDialog = new ProgressDialog(getActivity());
			progressDialog.setMessage("updating classroom");
			progressDialog.setIndeterminate(true);
			progressDialog.setCancelable(true);
			progressDialog.show();

		}

		protected String doInBackground(String... args) {

			try {

				ResultSet rs = DatabaseConnector.getStatement().executeQuery(
						"SELECT CONCAT(users.title, \" \",users.firstname, \" \", users.lastname) AS 'instructor', "
						+ " forum.date_started, forum.date_end, forum.title, forum.cid, forum.sid, forum.title, forum.cid, forum.sid,"
						+ " DATE_FORMAT(date_started,'%Y-%b-%d') AS 'started', DATE_FORMAT(date_end,'%Y-%b-%d') AS 'end', "
						+ " (SELECT DATEDIFF(date_end, NOW())) AS 'expiration', forum.isPinned, forum.isThread, forum.id FROM forum"
						+ " INNER JOIN schedule ON schedule.id = forum.sid"
						+ " INNER JOIN users ON users.id = forum.uid"
						+ " WHERE isThread = 1 OR isThread = 2 AND forum.sid = " + getScheduleID());

				while (rs.next()) {
				
					//TODO: showing excluding expired posts [if (!(rs.getInt("expiration") <= 1) || (rs.getInt("isPinned") == 1)) {]
//					if ((rs.getInt("expiration") <= 1) || (rs.getInt("isPinned") == 1)) {
					m = new HashMap<String, String>();
					m.put(KEY_TITLE, rs.getString("forum.title"));
					m.put(KEY_PERSON, rs.getString("instructor"));
					m.put(KEY_DATE_STARTED,  rs.getString("started"));
					m.put(KEY_DATE_END,  rs.getString("end"));
					m.put(KEY_IS_THREAD, rs.getString("isThread"));
					m.put(KEY_FORUM_ID, rs.getString("forum.id"));
					arrayList.add(m);
						
//						rowCount = arrayList.size();
//					}
						
					//TODO: show all posts (pinned, expired)
					
				}
				
				rowCount = rs.last() ? rs.getRow() : 0;
				

			} catch (SQLException e) {
				DatabaseConnector.Logger(getClass(), "doInBackground", e);
			}

			return null;
		}

		protected void onPostExecute(String postExecute) {

			TextView msg = new TextView(getActivity());
			
			if (rowCount == 0) {
				msg.setText("no topics available");
			} else if (rowCount == 1) {
				msg.setText("found " + rowCount + " topic.");
			} else if (rowCount > 1) {
				msg.setText("found " + rowCount + " topics.\n(Showing only pinned and open topics)");
			}

			msg.setTextAppearance(getActivity(), R.style.alert_message);
			msg.setGravity(Gravity.CENTER_HORIZONTAL);

			new AlertDialog.Builder(getActivity())
			.setTitle("Information")
			.setIcon(android.R.drawable.ic_dialog_info)
			.setView(msg)
			.setCancelable(false)
			.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					dialog.dismiss();
				}
			}).create().show();

			progressDialog.dismiss();

			getActivity().runOnUiThread(new Runnable() {

				@Override
				public void run() {

					listAdapter = new SimpleAdapter(getActivity(), arrayList, R.layout.student_forum_detail, 
							new String[] {KEY_TITLE, KEY_DATE_STARTED, KEY_DATE_END, KEY_PERSON, KEY_FORUM_ID}, 
							new int[] {R.id.tv_title, R.id.tv_date_started, R.id.tv_date_end, R.id.tv_key_person});

					setListAdapter(listAdapter);
				}
			});
		}
	} 

}